import json
import requests
import os

def handler_factory(model:str,api_key:str,base_url:str="https://api.deepseek.com"):
    """
    Factory function to create a handler for the specified model.
    """
    def handler(query:str):
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        data={
            "model":model,
            "messages":[{"role":"user","content":query}],
            "stream":True
        }
        response=requests.post(
            f"{base_url}/v1/chat/completions",
            headers=headers,
            json=data,
            stream=True
        )
        for line in response.iter_lines():
            # print(line.decode("utf-8"))
            if line and line.startswith(b"data: "):
                if line[len(b"data: "):].startswith(b"["):
                    return {"message":{"content":""}}
                chunk_data = json.loads(line[len(b"data: "):].decode("utf-8"))
                if chunk_data["choices"][0]["finish_reason"]=="Stop":
                    return {"message":{"content":""}}
                message = json.dumps({"message":{"content": chunk_data["choices"][0]["delta"]["content"]}})
                yield message
    return handler
    